<template>
  <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-900 mb-2">我的钱包</h1>
      <p class="text-gray-500">查看您的账户余额和交易记录</p>
    </div>

    <div class="bg-blue-50 rounded-lg p-6 mb-8">
      <div class="flex items-start justify-between mb-4">
        <div>
          <div class="text-sm text-gray-600 mb-2">账户余额</div>
          <div class="text-4xl font-bold text-gray-900 mb-2">¥{{ income.available.toFixed(2) }}</div>
          <div class="flex items-center gap-2 text-sm text-gray-600">可提现金额: ¥{{ income.available.toFixed(2) }}</div>
        </div>
        <button
          class="flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          @click="openWithdrawDialog"
        >
          提现
        </button>
      </div>
      <div class="grid grid-cols-3 gap-6 pt-4 border-t border-blue-100">
        <div>
          <div class="text-sm text-gray-600 mb-1">今日收入</div>
          <div class="text-2xl font-bold text-green-600">+¥{{ income.today.toFixed(2) }}</div>
        </div>
        <div>
          <div class="text-sm text-gray-600 mb-1">本月收入</div>
          <div class="text-2xl font-bold text-green-600">+¥{{ income.month.toFixed(2) }}</div>
        </div>
        <div>
          <div class="text-sm text-gray-600 mb-1">累计收入</div>
          <div class="text-2xl font-bold text-gray-900">¥{{ income.total.toFixed(2) }}</div>
        </div>
      </div>
    </div>

    <div class="mb-8">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-lg font-semibold text-gray-900">我的提现申请</h2>
      </div>
      <div class="space-y-3">
        <div
          v-for="r in withdrawRecords"
          :key="r.id"
          class="flex items-center justify-between p-4 rounded-lg border border-gray-200"
        >
          <div>
            <div class="font-medium text-gray-900">提现 ¥{{ Number(r.amount || 0).toFixed(2) }}</div>
            <div class="text-sm text-gray-600 mt-1">
              方式：{{ r.method === 'wechat' ? '微信钱包' : (r.method || '其他') }}
            </div>
          </div>
          <div class="text-right">
            <div
              class="text-sm font-semibold mb-1"
              :class="r.status === 1 ? 'text-yellow-600' : r.status === 2 ? 'text-green-600' : 'text-red-600'"
            >
              {{ r.status === 1 ? '待处理' : r.status === 2 ? '成功' : '失败' }}
            </div>
            <div class="text-xs text-gray-500">{{ formatDateTime(r.created_at) }}</div>
          </div>
        </div>
        <div v-if="!withdrawRecords.length" class="text-sm text-gray-500 text-center py-6">
          暂无提现申请记录
        </div>
      </div>
    </div>

    <div class="mb-8">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-lg font-semibold text-gray-900">交易记录</h2>
        <div class="flex gap-3">
          <select
            v-model="timeFilter"
            class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="30">最近30天</option>
            <option value="7">最近7天</option>
            <option value="90">最近90天</option>
          </select>
          <select
            v-model="typeFilter"
            class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="all">全部类型</option>
            <option value="income">收入</option>
            <option value="expense">支出</option>
          </select>
        </div>
      </div>
      <div class="space-y-3">
        <div
          v-for="tx in filteredTransactions"
          :key="tx.id"
          class="flex items-center justify-between p-4 rounded-lg"
          :class="tx.amount > 0 ? 'bg-green-50' : 'bg-red-50'"
        >
          <div class="flex items-center gap-4">
            <div
              class="w-10 h-10 rounded-full flex items-center justify-center"
              :class="tx.amount > 0 ? 'bg-green-100' : 'bg-red-100'"
            >
              <!-- 收入 / 支出 图标 -->
              <svg v-if="tx.amount > 0" xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M12 19V5m0 0l-4 4m4-4l4 4" />
              </svg>
              <svg v-else xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M12 5v14m0 0l-4-4m4 4l4-4" />
              </svg>
            </div>
            <div>
              <div class="font-medium text-gray-900">{{ tx.typeText }}</div>
              <div class="text-sm text-gray-600">{{ tx.desc }}</div>
            </div>
          </div>
          <div class="text-right">
            <div
              class="text-lg font-bold"
              :class="tx.amount > 0 ? 'text-green-600' : 'text-red-600'"
            >
              {{ tx.amount > 0 ? '+' : '' }}¥{{ Math.abs(tx.amount).toFixed(2) }}
            </div>
            <div class="text-sm text-gray-600">{{ tx.date }}</div>
          </div>
        </div>
        <div v-if="!transactions.length" class="text-sm text-gray-500 text-center py-6">
          暂无交易记录
        </div>
      </div>
    </div>

    <div>
      <h2 class="text-lg font-semibold text-gray-900 mb-4">提现设置</h2>
      <div class="space-y-3">
        <div class="flex items-center justify-between p-4 border border-gray-200 rounded-lg">
          <div class="flex items-center gap-4">
            <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
              <!-- 微信图标：双气泡，更大尺寸 -->
              <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7 text-green-500" viewBox="0 0 24 24" fill="currentColor">
                <path d="M10.2 4C6.76 4 4 6.3 4 9.06c0 1.7.93 3.07 2.4 4.06L6 15.5l2.06-1.1c.64.18 1.31.27 2.14.27 3.44 0 6.2-2.16 6.2-4.83C16.4 6.3 13.64 4 10.2 4Zm-2.2 3a.85.85 0 1 1 0 1.7.85.85 0 0 1 0-1.7Zm4.4 0a.85.85 0 1 1 0 1.7.85.85 0 0 1 0-1.7Z"/>
                <path d="M18 9.8c2.22.42 3.8 2 3.8 3.96 0 2.35-2.16 4.24-4.9 4.24-.6 0-1.17-.07-1.7-.22L12 19.5l.64-1.8c-.98-.76-1.54-1.76-1.54-2.94 0-2.22 1.98-3.98 4.54-3.98.8 0 1.55.17 2.36.42ZM15.7 13a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm3 0a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"/>
              </svg>
            </div>
            <div>
              <div class="font-medium text-gray-900">微信钱包</div>
              <div class="text-sm text-gray-600">已绑定: 微信账号</div>
            </div>
          </div>
          <span class="px-3 py-1 bg-blue-50 text-blue-600 text-sm rounded-full">默认</span>
        </div>
        <div class="flex items-center justify-between p-4 border border-gray-200 rounded-lg">
          <div class="flex items-center gap-4">
            <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
              <!-- 支付宝图标 -->
              <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-blue-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                <rect x="4" y="4" width="16" height="16" rx="4"/>
                <path stroke-linecap="round" stroke-linejoin="round" d="M8 10h8M9 14h6M10 7h4"/>
              </svg>
            </div>
            <div>
              <div class="font-medium text-gray-900">支付宝</div>
              <div class="text-sm text-gray-400">敬请期待</div>
            </div>
          </div>
          <button class="px-4 py-2 bg-gray-300 text-gray-500 rounded-lg cursor-not-allowed" disabled>绑定</button>
        </div>
        <div class="flex items-center justify-between p-4 border border-gray-200 rounded-lg">
          <div class="flex items-center gap-4">
            <div class="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center">
              <!-- 银行卡图标 -->
              <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-gray-600" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                <rect x="3" y="6" width="18" height="12" rx="2"/>
                <path d="M3 10h18"/>
                <path d="M7 14h4" stroke-linecap="round"/>
              </svg>
            </div>
            <div>
              <div class="font-medium text-gray-900">银行卡</div>
              <div class="text-sm text-gray-400">敬请期待</div>
            </div>
          </div>
          <button class="px-4 py-2 bg-gray-300 text-gray-500 rounded-lg cursor-not-allowed" disabled>绑定</button>
        </div>
      </div>
    </div>
    <!-- 提现弹窗 -->
    <div
      v-if="showWithdrawDialog"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-30"
    >
      <div class="bg-white rounded-lg shadow-lg w-full max-w-md p-6">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">申请提现</h3>
        <p class="text-sm text-gray-600 mb-4">当前可提现金额：<span class="font-semibold text-gray-900">¥{{ income.available.toFixed(2) }}</span></p>
        <div class="mb-4">
          <label class="block text-sm text-gray-700 mb-1">提现金额</label>
          <input
            v-model="withdrawAmount"
            type="number"
            min="0"
            step="0.01"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            placeholder="请输入提现金额，最低10元"
          />
        </div>
        <div class="mb-4">
          <label class="block text-sm text-gray-700 mb-2">提现方式</label>
          <div class="space-y-2">
            <label class="flex items-center justify-between p-3 border rounded-lg cursor-pointer">
              <div class="flex items-center gap-3">
                <input type="radio" value="wechat" v-model="withdrawMethod" class="text-blue-600" />
                <span class="text-sm text-gray-800">微信钱包</span>
              </div>
              <span class="text-xs text-blue-600">推荐</span>
            </label>
            <label class="flex items-center justify-between p-3 border rounded-lg bg-gray-50 cursor-not-allowed">
              <div class="flex items-center gap-3">
                <input type="radio" disabled class="text-gray-400" />
                <span class="text-sm text-gray-400">支付宝（敬请期待）</span>
              </div>
            </label>
            <label class="flex items-center justify-between p-3 border rounded-lg bg-gray-50 cursor-not-allowed">
              <div class="flex items-center gap-3">
                <input type="radio" disabled class="text-gray-400" />
                <span class="text-sm text-gray-400">银行卡（敬请期待）</span>
              </div>
            </label>
          </div>
        </div>
        <p class="text-xs text-gray-500 mb-4">单次最低提现金额为 10 元。提现申请提交后，将由支付服务处理打款，请耐心等待。</p>
        <div class="flex justify-end gap-3 mt-4">
          <button
            type="button"
            class="px-4 py-2 text-sm text-gray-600 rounded-lg hover:bg-gray-100"
            @click="closeWithdrawDialog"
          >
            取消
          </button>
          <button
            type="button"
            class="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-60"
            :disabled="withdrawLoading"
            @click="submitWithdraw"
          >
            {{ withdrawLoading ? '提交中...' : '确认提现' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'CourierWallet',
  data() {
    return {
      income: {
        total: 0,
        today: 0,
        month: 0,
        available: 0
      },
      transactions: [],
      withdrawRecords: [],
      timeFilter: '30',
      typeFilter: 'all',
      showWithdrawDialog: false,
      withdrawAmount: '',
      withdrawMethod: 'wechat',
      withdrawLoading: false
    }
  },
  computed: {
    filteredTransactions() {
      const days = Number(this.timeFilter || 30)
      const now = Date.now()
      const msRange = days * 24 * 60 * 60 * 1000
      return this.transactions.filter(tx => {
        // 时间范围
        if (tx.timestamp) {
          const delta = now - tx.timestamp
          if (delta < 0 || delta > msRange) return false
        }
        // 类型筛选
        if (this.typeFilter === 'income') {
          return tx.amount > 0
        }
        if (this.typeFilter === 'expense') {
          return tx.amount < 0
        }
        return true
      })
    }
  },
  methods: {
    formatDateTime(str) {
      if (!str) return ''
      try {
        const d = new Date(str)
        if (Number.isNaN(d.getTime())) return String(str)
        const y = d.getFullYear()
        const m = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        const hh = String(d.getHours()).padStart(2, '0')
        const mm = String(d.getMinutes()).padStart(2, '0')
        return `${y}-${m}-${day} ${hh}:${mm}`
      } catch {
        return String(str)
      }
    },
    openWithdrawDialog() {
      this.withdrawAmount = ''
      this.withdrawMethod = 'wechat'
      this.showWithdrawDialog = true
    },
    closeWithdrawDialog() {
      if (this.withdrawLoading) return
      this.showWithdrawDialog = false
    },
    async submitWithdraw() {
      const amountNum = Number(this.withdrawAmount)
      const minAmount = 10
      if (!amountNum || Number.isNaN(amountNum) || amountNum <= 0) {
        alert('请输入有效的提现金额')
        return
      }
      if (amountNum < minAmount) {
        alert(`单次最低提现金额为 ${minAmount} 元`)
        return
      }
      if (amountNum > this.income.available) {
        alert('提现金额不能超过可提现余额')
        return
      }
      if (this.withdrawMethod !== 'wechat') {
        alert('目前仅支持微信提现，其他方式敬请期待')
        return
      }

      const userId = localStorage.getItem('userId')
      if (!userId) {
        alert('请先登录')
        this.$router.push('/login')
        return
      }

      try {
        this.withdrawLoading = true
        const payload = {
          userId: Number(userId),
          amount: amountNum,
          method: 'wechat'
        }
        const { data } = await axios.post('/api/wallet/withdraw', payload)
        if (!data || data.success === false) {
          alert((data && data.message) || '提现申请失败，请稍后再试')
        } else {
          alert('提现申请已提交，请等待支付处理结果')
          // 重新加载余额和交易记录
          await this.loadIncome()
          await this.loadTransactions()
          this.showWithdrawDialog = false
        }
      } catch (e) {
        console.error('提现申请失败', e)
        alert('提现申请失败，请稍后再试')
      } finally {
        this.withdrawLoading = false
      }
    },
    async loadIncome() {
      const userId = localStorage.getItem('userId')
      if (!userId) return
      try {
        const { data } = await axios.get(`/api/couriers/income/${userId}`)
        const inc = (data && data.data) || {}
        this.income.total = Number(inc.total || 0)
        this.income.today = Number(inc.today || 0)
        this.income.month = Number(inc.month || 0)
        // 前端先将可提现余额设置为累计收入
        // 后续在加载提现记录时，再根据成功提现金额进行扣减
        this.income.available = this.income.total
      } catch (e) {
        console.error('加载收入数据失败', e)
      }
    },
    async loadTransactions() {
      const userId = localStorage.getItem('userId')
      if (!userId) return
      try {
        const { data } = await axios.get(`/api/orders/courier/${userId}`)
        const list = (data && data.data) || []
        this.transactions = list
          .filter(o => o.status === 5 || o.status === '5')
          .sort((a, b) => new Date(b.completed_at || b.delivered_at || b.created_at) - new Date(a.completed_at || a.delivered_at || a.created_at))
          .map(o => {
            const rawDate = o.completed_at || o.delivered_at || o.created_at || ''
            const finishedAt = rawDate.replace('T', ' ').slice(0, 16)
            const ts = rawDate ? new Date(rawDate).getTime() : null
            const amount = Number(o.final_fee || o.suggested_fee || 0)
            return {
              id: o.id,
              typeText: '订单收入',
              desc: `订单号: ${o.id}`,
              amount,
              date: finishedAt,
              timestamp: ts
            }
          })
      } catch (e) {
        console.error('加载交易记录失败', e)
      }
    },
    async loadWithdrawRecords() {
      const userId = localStorage.getItem('userId')
      if (!userId) return
      try {
        const { data } = await axios.get('/api/wallet/withdraw/my', {
          params: { userId: Number(userId) }
        })
        this.withdrawRecords = (data && data.data) || []

        // 重新计算可提现余额：累计收入 - 所有成功提现金额
        const successTotal = this.withdrawRecords
          .filter(r => r.status === 2 || r.status === '2')
          .reduce((sum, r) => sum + Number(r.amount || 0), 0)
        const available = this.income.total - successTotal
        this.income.available = available > 0 ? available : 0
      } catch (e) {
        console.error('加载提现申请记录失败', e)
      }
    }
  },
  mounted() {
    this.loadIncome()
    this.loadTransactions()
    this.loadWithdrawRecords()
  }
}
</script>
